#!/usr/bin/env python

# Publishr to publish images on web
# Copyright (C) 2007  Jayesh Salvi 
# http://www.altcanvas.com
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

import gtk
import libpub
import oauth2 as oauth
import time
import StringIO
import gzip
from lxml import etree
from libpub.twitter_oauth import authCodes

########################################
# Twitpic API
########################################

class TwitpicObject:
    twitpic=None
    oauth_token=None
    oauth_token_secret=None

    _has_auth = False
    def __init__(self):
        last_oauth_token = libpub.conf.get('TWITTER_OAUTH_TOKEN')
        last_oauth_token_secret = libpub.conf.get('TWITTER_OAUTH_TOKEN_SECRET')

        self.oauth_token=last_oauth_token
        self.oauth_token_secret=last_oauth_token_secret

        if last_oauth_token and last_oauth_token_secret:
            self._has_auth = True

    def login(self,username,password):
        self.oauth_token=username
        self.oauth_token_secret=password

        # TODO: check oauth credentials with twitter.com
        self._has_auth=username and password

    def has_auth(self):
        return self._has_auth

    def upload(self,filename,description,postToTwitter,service):
        img = self.InsertPhotoSimple(message = description, 
        	filename = filename, postToTwitter = postToTwitter, service = service)
        return img

    def InsertPhotoSimple(self,filename,message,postToTwitter,service):
        import sys, traceback
        import MultipartPostHandler, urllib2, cookielib

        cookies = cookielib.CookieJar()
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookies),
                                MultipartPostHandler.MultipartPostHandler)
        params = { "message":message,
                   "media":open(filename, "rb") }

        serviceUrl=''
        k=authCodes()
        extension='json'

        if service=='twitpic.com':
            serviceUrl='http://api.twitpic.com/2/upload.xml'
            params['key']=k.obf(k.tp())
        if service=='yfrog.com':
            serviceUrl='http://yfrog.com/api/xauth_upload'
            params['key']=k.obf(k.yf())
            extension='xml'
        if service=='twitgoo.com':
            serviceUrl='http://twitgoo.com/api/upload'
        if service=='posterous.com':
            serviceUrl='http://posterous.com/api2/upload.xml'
        if service=='img.ly':
            serviceUrl='http://img.ly/api/2/upload.xml'

        msg=''
        try:
            # Set the API endpoint 
            url = 'https://api.twitter.com/1/account/verify_credentials.'+extension

            # Set the base oauth_* parameters along with any other parameters required
            # for the API call.
            oauth_params={}
            oauth_params['oauth_version']="1.0";
            oauth_params['oauth_nonce']=oauth.generate_nonce()
            oauth_params['oauth_timestamp']=int(time.time())

            # Set up instances of our Token and Consumer. The Consumer.key and 
            # Consumer.secret are given to you by the API provider. The Token.key and
            # Token.secret is given to you after a three-legged authentication.
            token = oauth.Token(key=self.oauth_token, secret=self.oauth_token_secret)
            k=authCodes()
            consumer = oauth.Consumer(key=k.obf(k.ck()), secret=k.obf(k.cs()))

            # Set our token/key parameters
            oauth_params['oauth_token'] = token.key
            oauth_params['oauth_consumer_key'] = consumer.key

            # Create our request. The request is not executed since we use urllist2
            # TODO: should only use one lib
            req = oauth.Request(method="GET", url=url, parameters=oauth_params)

            # Sign the request.
            signature_method = oauth.SignatureMethod_HMAC_SHA1()
            req.sign_request(signature_method, consumer, token)

            authorization=req.to_header('http://api.twitter.com/')['Authorization'];

            req = urllib2.Request(serviceUrl, params)
            # TODO: setting Accept-Encoding doesn't work??
#            req.add_header('Accept-Encoding', 'identity')
            req.add_header('X-Auth-Service-Provider', url)
            req.add_header('X-Verify-Credentials-Authorization', authorization)
            response=opener.open(req)
            msg = response.read()
            # decode gzip for response (would be easier to turn off gzip in the request)
            if response.headers.get('content-encoding', '') == 'gzip':
                gzipper = gzip.GzipFile(fileobj=StringIO.StringIO(msg))
                msg = gzipper.read()
        except Exception, e:
            libpub.alert('Upload exception: %s'%e)
            libpub.alert('%s'%traceback.format_exc())

        if msg=='':
            return False

        libpub.alert('Reply: %s'%msg)

        if postToTwitter=='1':
            file_data = etree.parse(StringIO.StringIO(msg))

            url=''
            for item in file_data.iter('url'):
                url=item.text
            for item in file_data.iter('mediaurl'):
                url=item.text

            # after getting the image url, post the message to twitter
            fullmessage=message+" "+url

            try:
                # Set the API endpoint 
                url = 'http://api.twitter.com/1/statuses/update.xml'

                # Set up instances of our Token and Consumer. The Consumer.key and 
                # Consumer.secret are given to you by the API provider. The Token.key and
                # Token.secret is given to you after a three-legged authentication.
                token = oauth.Token(key=self.oauth_token, secret=self.oauth_token_secret)
                k=authCodes()
                consumer = oauth.Consumer(key=k.obf(k.ck()), secret=k.obf(k.cs()))

                client=oauth.Client(consumer, token)

                resp, content = client.request(url, 'POST', 'status='+fullmessage)
                msg='msg:'%resp+content

            except Exception, e:
                libpub.alert('Post exception: %s'%e)
                libpub.alert('%s'%traceback.format_exc())

            libpub.alert(msg)

        return True

